<?php
class BankNameField extends TextField {
	private static $allowed_actions = array(
        'get_bank_list'
    );
	
	/**
     * The url to use as the check bank list
     * @var string
     */
    protected $bankListURL;
	
	protected $countryField;

	public function __construct($name, $title = null, $value = '', $maxLength = null, $form = null) {
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
        Requirements::javascript('member/javascript/BankNameField.min.js');
		parent::__construct($name, $title, $value, $maxLength, $form);
	}
	
	function getAttributes() {
        return array_merge(
            parent::getAttributes(), array(
            	'rel' => 'bankname',
                'data-url' => $this->getBankListURL(),
                'data-country-field' => $this->getCountryField()
            )
        );
    }
	
	function Type() {
		return 'bankname text';
	}
	
	/**
     * Set the URL used to get bank list.
     * 
     * @param string $URL The URL used for get bank list.
     */
    function setBankListURL($url) {
        $this->bankListURL = $url;
    }
	
	/**
     * Get the URL used to get bank list.
     *  
     * @return The URL used for get bank list.
     */
    function getBankListURL() {

        if (!empty($this->bankListURL)){
            return $this->bankListURL;
		}

        // Attempt to link back to itself
        return $this->Link('get_bank_list');
    }
	
	/**
     * Set the country field used for get bank list.
     * 
     * @param string $country_field The country field used for get bank list.
     */
    function setCountryField($country_field) {
        $this->countryField = $country_field;
		return $this;
    }
	
	/**
     * Get the country field used to get bank list.
     *  
     * @return The URL used for get bank list.
     */
    function getCountryField() {
        return $this->countryField;
    }

	/**
     * Handle a request for bank list checking.
     * 
     * @param HTTPRequest $request The request to handle.
     * @return bank list result
     */
    function get_bank_list(HTTPRequest $request) {
		if(($country = $request->getVar('country')) && singleton('BankList')->mapByCountry($country)->count()) {
			return singleton('BankList')->getDropdownFieldByCountry($country, $this->getName(), $this->Title())->setValue($this->Value())->setForm($this->getForm())->setAttribute('rel', 'bankname')->setAttribute('data-url', $this->getBankListURL())->setAttribute('data-country-field', $this->getCountryField())->Field();
		}
		
		return $this->Field();
    }
}
?>
